'use strict';

const axios = require('axios')
const semver = require('semver')
const urlJoin = import('url-join')

async function getNpmInfo(npmName, registry) {
    if(!npmName) return;
    const registrites = registry || getDefauleRegistry()
    const npmInfoUrl = (await urlJoin).default(registrites, npmName)
    return axios.get(npmInfoUrl).then(res => {
        return res.status == 200 ?  res.data : null
    }).catch(err => {
        return Promise.reject(err)
    })
} 

function getDefauleRegistry(isOriginal = true ){
  return isOriginal ? 
    "https://registry.npmjs.org" :
    "https://registry.npm.taobao.org"
}

// 获取npm中的版本信息
async function getNpmVersions(npmName, registry){
   const data = await getNpmInfo(npmName, registry) 
   return data ? Object.keys(data.versions) : []
}

// 获取semver比对后的版本信息
function getSemverVersions(baseVersion, versions){
    return versions
            .filter(version => semver.satisfies(version, `^${baseVersion}`))
            .sort((a, b) => semverSort(b, a))
}

async function getNpmSemverVersion(baseVersion, npmName, registry){
    const versions = await getNpmVersions(npmName, registry)
    const newVersions = getSemverVersions(baseVersion, versions)
    if(newVersions && newVersions.length > 0) return newVersions[0]
}

function semverSort(b, a){
    return semver.gt(b, a) ? 1 : -1;
}
async function getNpmLatestVersion(npmName, registry) {
    let versions = await getNpmVersions(npmName, registry) 
    if(versions){
        return  versions.sort((a, b) => semverSort(b, a))[0]
    }
    return null
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion,
    getDefauleRegistry,
    getNpmLatestVersion
}